from flask import Blueprint, request
from common.libs.Helper import ops_renderJSON, ops_renderErrJSON
from common.models.employ_list import EmployList
from common.models.employ_order import EmployOrder
from common.models.department import Department
from common.models.user import User
from common.models.project import Project
from application import db
from common.libs.DataHelper import getCurrentTime, getCurrentDate
from flask import json
import datetime
from sqlalchemy import func
import requests
import urllib.request
from flask import Blueprint,render_template,request
from common.libs.Helper import ops_renderJSON,ops_renderErrJSON,ops_render
from common.models.document import Document
from application import db
from flask import request,json
from qiniu import Auth
from qiniu import put_data
import time

employ_page = Blueprint("employ_page", __name__)
# 用户展示岗位列表
@employ_page.route("/showemploylist", methods=["GET", "POST"])
def showemploylist():
    a = EmployList.query.filter(EmployList.mark ==1).all()
    rts = []
    for item in a:
        date=str(item.created_time)
        temp = dict(name=item.name, company=item.company, department=item.department, describe=item.describe, id=item.id,award=item.award,date= date,city=item.city,phone=item.creater.phone,creater=item.creater.nickname)
        rts.append(temp)
    # rts = json.dumps(a, cls=AlchemyEncoder,ensure_ascii=False)
    return json.dumps(rts, ensure_ascii=False)  # rts

# 展示用户的已举荐列表
@employ_page.route("/showmylist", methods=["GET", "POST"])
def showMyList():
    req = request.values
    uid = req['uid'] if "uid" in req else ""

    a = EmployOrder.query.filter_by(uid=uid,mark=1).all()
    rts = []
    for item in a:
        date = str(item.updated_time)
        temp = dict(name=item.employpost.name,id=item.id,date=date,status=item.status,name2=item.name)
        rts.append(temp)
    # rts = json.dumps(a, cls=AlchemyEncoder,ensure_ascii=False)
    return json.dumps(rts, ensure_ascii=False)  # rts


# 管理员添加岗位
@employ_page.route('/postemployorder', methods=['GET', 'POST'])
def postemployorder():
    req = request.values
    name = req['name'] if "name" in req else ""
    company = req['company'] if "company" in req else ""
    department = req['department'] if "department" in req else ""
    describe = req['describe'] if "describe" in req else ""
    city = req['city'] if "city" in req else ""
    award = req['award'] if "award" in req else ""
    uid = req['uid'] if "uid" in req else ""

    if len(name) < 1:
        return ops_renderErrJSON(msg="请输入名称")
    if len(describe) < 1:
        return ops_renderErrJSON(msg="请输入任职要求")

    if len(company) < 1 or company == "请选择":
        return ops_renderErrJSON(msg="请选择公司名称")

    if len(department) < 1 or department == "请选择":
        return ops_renderErrJSON(msg="请选择部门")

    if len(award) < 1:
        return ops_renderErrJSON(msg="请输入奖金")


    if len(city) < 1 or city == "请选择":
        return ops_renderErrJSON(msg="请选择城市")

    else:
        Order = EmployList()
        Order.name = name
        Order.company = company
        Order.department = department
        Order.city = city
        Order.describe =describe
        Order.award = award
        Order.mark = 1
        Order.uid = uid
        Order.created_time = Order.updated_time = getCurrentTime()
        db.session.add(Order)
        db.session.commit()

        return json.dumps({"code": 200, "msg": "添加成功", }, indent=4,
                          sort_keys=True, default=str,
        ensure_ascii=False)


# 用户提交举荐单
@employ_page.route('/postenlist', methods=['GET', 'POST'])
def postEnlist():
    req = request.values
    eid = req['eid'] if "eid" in req else ""
    uid = req['uid'] if "uid" in req else ""
    name = req['name'] if "name" in req else ""
    phone = req['phone'] if "phone" in req else ""


    if len(eid) < 1:
        return ops_renderErrJSON(msg="举荐失败")
    if len(uid) < 1:
        return ops_renderErrJSON(msg="举荐失败")
    if len(name) < 1:
        return ops_renderErrJSON(msg="请输入姓名")
    if len(phone) < 1:
        return ops_renderErrJSON(msg="请输入电话")
    else:
        Order = EmployOrder()
        Order.eid = eid
        Order.uid = uid
        Order.mark = 1
        Order.status = 0
        Order.name = name
        Order.phone = phone
        Order.created_time = Order.updated_time = getCurrentTime()

        db.session.add(Order)
        db.session.commit()

        return json.dumps({"code": 200, "msg": "举荐成功", }, indent=4,
                          sort_keys=True, default=str,
                          ensure_ascii=False)

# 管理员改变举荐单状态
@employ_page.route("/changestatus", methods=["GET", "POST"])
def changestatus():
    req = request.values
    id = req['id'] if "id" in req else ""
    status = req['status'] if "status" in req else ""
    name = req['name'] if "name" in req else ""
    time = getCurrentTime()
    a=EmployOrder.query.filter_by(id=id).first()
    openid = a.creater.openid
    if status == "3":
        appID = 'wx15624353af4493ad'  # 开发者关于微信小程序的appID
        appSecret = 'd7f09203305d4afe4716c0bdaa6fe7c7'  # 开发者关于微信小程序的appSecret
        req_params = {
            'appid': appID,
            'secret': appSecret,
            'grant_type': "client_credential"
        }
        wx_login_api = 'https://api.weixin.qq.com/cgi-bin/token?'
        response_data = requests.get(wx_login_api, params=req_params)  # 向API发起GET请求
        resData = response_data.json()
        token = resData['access_token']  # 得到用户关于当前小程序的OpenID

        data = {
            "touser": openid,
            "template_id": "RhQmy-1ihsDn84GG8VF8rS9YA5-097o9vDT5ZaPyxnQ",
            # "page": "pages/seal/sealmeg?pdnum=" + str(id),
            "page": "pages/index/index",
            "miniprogram_state": "formal",
            "lang": "zh_CN",
            "data": {
                "thing1": {
                    "value": "您举荐的人才"+name+"已通过面试"
                },
                "time2": {
                    "value": time
                },
                "thing3": {
                    "value": "您的人才举荐奖金即将发放，请及时查收"
                },
            }
        }

        url = 'https://api.weixin.qq.com/cgi-bin/message/subscribe/send?access_token={serverToken}'.format(
            serverToken=token)
        # 数据格式化(从这里开始对上面的data进行格式化,转成符合post的json参数形式)
        data = json.dumps(data)
        # 数据格式化
        data = bytes(data, 'utf8')
        # 数据格式化

        request1 = urllib.request.Request(url)
        # post服务器请求
        result = urllib.request.urlopen(request1, data).read()

        # 打印结果
        newresult = json.loads(result)
        errcode = newresult['errcode']
        if errcode == 0:
            a = EmployOrder.query.filter_by(id=id).first()
            a.status = status
            db.session.commit()
            return ops_renderJSON(msg="已成功通知")

        if errcode == 43101:
            a = EmployOrder.query.filter_by(id=id).first()
            a.status = status
            db.session.commit()
            return ops_renderJSON(msg="员工拒绝通知")
    else:
        a = EmployOrder.query.filter_by(id=id).first()
        a.status = status
        db.session.commit()
        return ops_renderJSON(msg="状态更新成功")



    req = request.values
    id = req['id'] if "id" in req else ""
    status = req['status'] if "status" in req else ""
    a = EmployOrder.query.filter_by(id=id).first()
    a.status = status
    db.session.commit()
    return ops_renderJSON(msg="状态变更成功")

# 关闭举荐单
@employ_page.route("/changemark", methods=["GET", "POST"])
def changemark():
    req = request.values
    id = req['id'] if "id" in req else ""
    mark = req['mark'] if "mark" in req else ""
    a = EmployOrder.query.filter_by(id=id).first()
    a.mark = mark
    db.session.commit()
    return ops_renderJSON(msg="状态变更成功")


# 管理员删除岗位
@employ_page.route("/changelistmark", methods=["GET", "POST"])
def changelistmark():
    req = request.values
    id = req['id'] if "id" in req else ""
    mark = req['mark'] if "mark" in req else ""
    a = EmployList.query.filter_by(id=id).first()
    a.mark = mark
    db.session.commit()

    b= EmployOrder.query.filter_by(eid=id).all()
    for item in b :
        item.mark=0
        db.session.commit()
    return ops_renderJSON(msg="状态变更成功")


@employ_page.route("/showadminlist", methods=["GET", "POST"])
def showAdminList():
    req = request.values
    city = req['city'] if "city" in req else ""
    mark = req['mark'] if "mark" in req else ""

    a = EmployList.query.filter_by(mark = mark, city = city,).all()
    rts = []
    for item in a:
        date=str(item.created_time)
        temp = dict(name=item.name, company=item.company, department=item.department, describe=item.describe, id=item.id,award=item.award,date=date)
        rts.append(temp)
        # rts = json.dumps(a, cls=AlchemyEncoder,ensure_ascii=False)
    return json.dumps(rts, ensure_ascii=False)  # rts



@employ_page.route("/getemploydetail", methods=["GET", "POST"])
def getEmploydetail():
    req = request.values
    id = req['id'] if "id" in req else ""
    a = EmployOrder.query.filter_by(eid=id, mark=1).all()
    rts = []
    for item in a:
        date=str(item.created_time)
        temp = dict(id=item.id, name=item.name,poster=item.creater.nickname,company=item.creater.company,userphone=item.creater.phone,department=item.creater.department,mark=item.mark,status=item.status,date=date,phone=item.phone)
        rts.append(temp)
    # rts = json.dumps(a, cls=AlchemyEncoder,ensure_ascii=False)
    return json.dumps(rts, ensure_ascii=False)  # rts
#
#
# @employ_page.route("/getstudydetail2", methods=["GET", "POST"])
# def getEmploydetail2():
#     req = request.values
#     id = req['id'] if "id" in req else ""
#     a = EmployOrder.query.filter_by(sid=id, mark=2).all()
#     rts = []
#     for item in a:
#         temp = dict(id=item.id, student=item.creater.nickname,company=item.creater.company,department=item.creater.department,mark=item.mark)
#         rts.append(temp)
#     # rts = json.dumps(a, cls=AlchemyEncoder,ensure_ascii=False)
#     return json.dumps(rts, ensure_ascii=False)  # rts


@employ_page.route('/admin', methods=['GET', 'POST'])
def index():
    return ops_render("/admin/employadmin.html")

@employ_page.route('/post', methods=['GET', 'POST'])
def employ_post():

    describe = request.form.get('describe')
    name = request.form.get('name')
    company = request.form.get('company')
    department = request.form.get('department')
    city = request.form.get('city')
    award = request.form.get('award')
    uid=request.form.get('uid')


    Order = EmployList()
    Order.name = name
    Order.company = company
    Order.department = department
    Order.city = city
    Order.describe = describe
    Order.award = award
    Order.mark = 1
    Order.uid = uid
    Order.created_time = Order.updated_time = getCurrentTime()
    db.session.add(Order)
    db.session.commit()


    return ops_render("/admin/employadmin.html")